<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="课程名称" prop="courseId">
        <el-select v-model="formData.courseId" placeholder="请输入课程">
        <el-option
          v-for="item in courseList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="commodityName">
        <el-input v-model="formData.commodityName" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="老师姓名" prop="teacherId">
        <el-select v-model="formData.teacherId" placeholder="请输入课程商品授课老师">
          <el-option
            v-for="item in teacherList"
            :key="item.id"
            :label="item.teacherName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="封面" prop="courseCoverUrl">
        <UploadImg v-model="formData.courseCoverUrl" />
      </el-form-item>
      <el-form-item label="课程商品价格" prop="commodityPrice">
        <el-input v-model="formData.commodityPrice" placeholder="请输入课程商品价格" />
      </el-form-item>
      <el-form-item label="授课总时长" prop="teachingAllTime">
        <el-input v-model="formData.teachingAllTime" placeholder="请输入授课总时长" />
      </el-form-item>
      <el-form-item label="每次授课时长" prop="teachingTime">
        <el-input v-model="formData.teachingTime" placeholder="请输入每次授课时长" />
      </el-form-item>
      <el-form-item label="开课时间" prop="beginTime">
        <el-date-picker
          v-model="formData.beginTime"
          type="date"
          value-format="x"
          placeholder="选择开课时间"
        />
      </el-form-item>
      <el-form-item label="结课时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="date"
          value-format="x"
          placeholder="选择结课时间"
        />
      </el-form-item>
      <el-form-item label="vip标识" prop="vipFlag">
        <el-radio-group v-model="formData.vipFlag">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.TRAIN_COMMODITY_VIP_FLAG)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="课程标记" prop="courseFlag">
        <el-select v-model="formData.courseFlag" placeholder="请选择课程标记">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TRAIN_COMMODITY_FLAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择上架状态">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TRAIN_COURSE_COMMODITY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CourseCommodityApi, CourseCommodity } from '@/api/train/coursecommodity'
import {CourseApi} from "@/api/train/course";
import {TeacherApi} from "@/api/train/teacher";

/** 课程商品管理 表单 */
defineOptions({ name: 'CourseCommodityForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  courseId: undefined,
  teacherId: undefined,
  courseCoverUrl: undefined,
  commodityPrice: undefined,
  teachingAllTime: undefined,
  teachingTime: undefined,
  beginTime: undefined,
  endTime: undefined,
  vipFlag: undefined,
  applicantNumber: undefined,
  courseFlag: undefined,
  teacherName: undefined,
  name: undefined,
  commodityName: undefined,
  status: undefined
})
const formRules = reactive({
  courseId: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
  commodityName: [{required: true, message: '商品名称不能为空', trigger: 'blur'}],
  teacherId: [{required: true, message: '授课老师不能为空', trigger: 'blur'}],
  courseCoverUrl: [{required: true, message: '商品封面不能为空', trigger: 'blur'}],
  commodityPrice: [{ required: true, message: '商品价格不能为空', trigger: 'blur' }],
  teachingAllTime: [{required: true, message: '授课总时长不能为空', trigger: 'blur'}],
  teachingTime: [{required: true, message: '授课单次时长不能为空', trigger: 'blur'}],
  beginTime: [{required: true, message: '开课时间不能为空', trigger: 'blur'}],
  endTime: [{ required: true, message: '结课时间不能为空', trigger: 'blur' }],
  vipFlag: [{required: true, message: '会员标识不能为空', trigger: 'blur'}],
  courseFlag: [{required: true, message: '课程标识不能为空', trigger: 'blur'}],
  status: [{required: true, message: '商品上架状态不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

const loading = ref(true) // 列表的加载中



const courseList = ref(null)
const teacherList = ref(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const courseData = await CourseApi.getCourseList(null)
    courseList.value = courseData

    const TeacherData = await TeacherApi.getTeacherList(null)
    teacherList.value = TeacherData
  } finally {
    loading.value = false
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {

  getList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CourseCommodityApi.getCourseCommodity(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CourseCommodity
    if (formType.value === 'create') {
      await CourseCommodityApi.createCourseCommodity(data)
      message.success(t('common.createSuccess'))
    } else {
      await CourseCommodityApi.updateCourseCommodity(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    courseId: undefined,
    teacherId: undefined,
    courseCoverUrl: undefined,
    commodityPrice: undefined,
    teachingAllTime: undefined,
    teachingTime: undefined,
    beginTime: undefined,
    endTime: undefined,
    vipFlag: undefined,
    applicantNumber: undefined,
    courseFlag: undefined
  }
  formRef.value?.resetFields()
}
</script>
